import os
from time import sleep

import pyautogui as pyautogui
import pyperclip
from selenium import webdriver
# 实现反爬虫检测
from selenium.webdriver import ChromeOptions
from selenium.webdriver.common.action_chains import ActionChains

if __name__ == "__main__":
    # 创建一个参数对象
    option = ChromeOptions()

    # 控制chrome以无界面模式打开
    # option.add_argument('--headless')
    # option.add_argument('--disable-gpu')

    # 实现反爬虫检测
    option.add_experimental_option('excludeSwitches', ['enable-automation'])
    # 禁止加载css
    prefs = {'permissions.default.stylesheet': 2}
    option.add_experimental_option("prefs", prefs)

    bro = webdriver.Chrome(executable_path="../chromedriver/84.0.4147.30/chromedriver", options=option)
    # 隐性等待，最长等30秒
    bro.implicitly_wait(30)

    # 金田一第23卷
    base_url = "https://www.manhuagui.com/comic/4756/43458.html#p="
    num = "23/"
    base_pic_path = "./pic/webp/" + num

    # range(1, 186)，i的取值范围是从1到185，不包括186
    for i in range(1, 190):
        bro.get(base_url + str(i))
        img_tag = bro.find_element_by_id("mangaFile")
        img_url = img_tag.get_attribute("src")

        # 漫画图片URL：https://i.hamreus.com/ps1/j/jty/27/000.png.webp?e=1598778685&m=0Bo2Q8rklsdB2cj7RrrOmg
        # print(img_url)
        bro.get(img_url)
        # 定位img元素
        img_tag = bro.find_element_by_xpath("/html/body/img")

        action = ActionChains(bro).move_to_element(img_tag)  # 移动到该元素
        action.context_click(img_tag).perform()  # 右键点击该元素
        pyautogui.typewrite(['v'])  # 敲击V进行保存

        absp = os.path.abspath(base_pic_path)
        if not os.path.exists(absp):  # 指定的目录是否存在
            os.makedirs(absp)

        pic_dir = absp + "\\" + str(i)
        # print(pic_dir)
        # 将地址以及文件名复制
        pyperclip.copy(pic_dir)

        # 单击图片另存之后等1s敲回车
        sleep(0.9)
        # 粘贴
        pyautogui.hotkey('ctrlleft', 'V')
        # 确认保存
        pyautogui.press('enter')

    # 关闭浏览器
    bro.quit()
